<template>
  <label class="s-radio" :class="[{ 'is-checked': model === label }]">
    <span class="el-radio__input">
      <input
        type="radio"
        v-model="model"
        :disabled="isDisabled"
        :value="label"
        @change="handleChange"
      />
    </span>
    <span class="el-radio__label">
      <slot></slot>
      <template v-if="!$slots.default">{{label}}</template>
    </span>
  </label>
</template>

<script>
import Emitter from "@/mixin/emitter";
export default {
  name: "SRadio",
  props: ["value", "label"],
  mixins: [Emitter],
  data() {
    return {
      radioGroups: ""
    };
  },
  computed: {
    isGroup() {
      let parent = this.$parent;
      while (parent) {
        if (parent.$options.componentName !== "SRadioGroup") {
          parent = parent.$parent;
        } else {
          this.changeData(parent);
          return true;
        }
      }
      return false;
    },
    isDisabled() {
      //   console.log("isDisabled", this.radioGroups.disabled);
      return this.isGroup ? this.radioGroups.disabled : this.disabled;
    },
    model: {
      get() {
        return this.isGroup ? this.radioGroups.value : this.value;
      },
      set(val) {
        if (this.isGroup) {
          this.dispatch("SRadioGroup", "input", [val]);
        } else {
          this.$emit("input", val);
        }
      }
    }
  },

  methods: {
    changeData(val) {
      this.radioGroups = val;
    },
    handleChange(val) {
      this.$nextTick(() => {
        this.$emit("changed", val.target.value);
        this.isGroup &&
          this.dispatch("SRadioGroup", "handleChange", val.target.value);
      });
    }
  }
};
</script>

<style>
</style>